<?php
namespace app\admin\controller;

use think\Controller;
use app\admin\model\Account as AccountModel;
use app\admin\model\Paylist as PaylistModel;
use app\admin\model\Withdrawlist as WithdrawModel;
use app\admin\model\User as UserModel;
use think\Session;
use think\Db;

//冻结的金币删除


class Bill extends AdminBase{
    //账单首页
    public function index(){

        

       

        //初始化模型

        $accountModel = new AccountModel();


        $data = $accountModel->paginate(10);

        $this->assign('data',$data);
        $page = $data->render();
         $total = $data->total();
         $count = $data->count();

        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('total',$total);
        $this->assign('count',$count);

        return $this->fetch();
    }

    //充值账单
    public function payIndex(){

     
        $payList = new PaylistModel();
        
        //$data = $payList->where('userid', $UserID)->select();
        $data = $payList->paginate(10);
         //dump($data);die;
        
        $this->assign('data',$data);
       
        
         $page = $data->render();
         $total = $data->total();
         $count = $data->count();

        $this->assign('data',$data);
        $this->assign('page',$page);
        $this->assign('total',$total);
        $this->assign('count',$count);
        return $this->fetch();
    }

    //提现申请
    public function withDraw(){
  
      
        $Model = new WithdrawModel();
        

        
        $data = $Model->paginate(10);

        $this->assign('data',$data);
        $page = $data->render();
        $total = $data->total();
        $count = $data->count();
        $this->assign('page',$page);
        $this->assign('total',$total);
        $this->assign('count',$count);

        
        return $this->fetch();
    }

    //后台申请提现同意，冻结的金币删除
    public function withDrawSET(){

        $withDrawInfo = input('get.');
        //dump($withDrawInfo);
        // file_put_contents('1.txt',$withDrawInfo['withDraw_id'],FILE_APPEND);
        $withDrawModel = new WithdrawModel();
            $result = $withDrawModel->save(['status'  => '1'],['id' => $withDrawInfo['withDraw_id']]);
        
    }
    //后台申请提现拒绝，冻结的金币重新存入当前账户中
    public function withDrawFAL(){

        $withDrawInfo = input('get.');
        //dump($withDrawInfo);
        // file_put_contents('1.txt',$withDrawInfo['withDraw_id'],FILE_APPEND);
        $withDrawModel = new WithdrawModel();
            $result = $withDrawModel->save(['status'  => '2'],['id' => $withDrawInfo['withDraw_id']]);
        
    }
    //后台充值申请同意，确认充值订单，确认之后，现金进入用户账户
    public function payIndexSET(){

        $withDrawInfo = input('get.');
        //dump($withDrawInfo);
         // file_put_contents('1.txt',$withDrawInfo['withDraw_id'],FILE_APPEND);
        // $withDrawInfo = '1';
        $payList = new PaylistModel();
         $result = $payList->save(['status'  => '1'],['id' => $withDrawInfo['withDraw_id']]);
        /*$result = $payList->save(
           
            ['status'  => '1'],
            ['id' => $withDrawInfo]
        );*/
        
       if($result){
            //echo "修改成功";
            //cash结算
            $userAccount = new AccountModel;
            $paymoney = $payList->where('id',$withDrawInfo['withDraw_id'])->find();
            $userAC = $userAccount -> where('user_id',$withDrawInfo['userid'])->find();
            //file_put_contents('1.txt',$userAC['cash'],FILE_APPEND);die;
            $acash = $userAC['cash']+$paymoney['pay_money'];
            //all_pay计算
            //file_put_contents('1.txt',$acash,FILE_APPEND);die;
            $apay = $userAC['allpay']+$paymoney['pay_money'];
            $userAccount->save([
                'cash'  => $acash,
                'allpay' => $apay
            ],['user_id' => $withDrawInfo['userid']]);
            return json_encode(1);
        }else{
            //echo "修改失败";
            return json_encode(0);
        }
    }
    //后台充值申请拒绝
    public function payIndexFAL(){

        $withDrawInfo = input('get.');
        //dump($withDrawInfo);
        //file_put_contents('1.txt',$withDrawInfo,FILE_APPEND);
        $payList = new PaylistModel();
        $result = $payList->save(['status'  => '2'],['id' => $withDrawInfo['withDraw_id']]);

            
    }

    
    //账户账单修改功能
    public function modifyBill(){
        $AllData = input('post.');
        //file_put_contents('1.txt',$AllData,FILE_APPEND);die;
        $User = new AccountModel();
        $change = explode(',', $AllData['userinfo_str']);
        //file_put_contents('1.txt',$change,FILE_APPEND);die;
        $SuccessArray = [];
        $FailArray = [];
        if($User->where(['id' => $change['0']])->find()){
            //存在就更新
            $Res = $User->save(
                [
                    'gold_coin'  => $change['8'],
                    'commodity_coin' => $change['9'],
                    'market_coin' => $change['10'],
                    'stock' => $change['11'],
                ],
                ['id' => $change['0']]);
            //给出成功标志
            $SuccessArray[] = 1;
            if($Res){
                //echo "111";
            }else{
               // echo '222';
            }
        }else{
            //不存在直接返回
            $FailArray []= 1;
         //   echo  'false';
        }
        //echo $result['id'];die;
        //返回的数组
        $StatusArray = [];
        $StatusArray['status'] = "1";
        $StatusArray['success'] = $SuccessArray ? $SuccessArray : NULL;
        //$StatusArray['success'] = ['aa','bb'];
        $StatusArray['fail'] = $FailArray ? $FailArray : NULL;

        // dump($StatusArray);die;
        //var_dump($StatusArray);die;
        return json_encode($StatusArray);
    }



    // 创建结算单
    public function createbill(){
        $UserID = Session::get('userid');
        $UserName = Session::get('username');
        $this->assign('username',$UserName);
        $this->assign('userid',$UserID);
        $lastinfo = db::name('user_bill')->order('id desc')->find();
        if (!empty($lastinfo)) {
            $year = $lastinfo['year'].'年'.$lastinfo['month'].'月';
        }else{
            $year = '';
        }
        $this->assign('year',$year);
        return $this->fetch();
    }
    public function createbillsubmit(){
        $post = input('post.');
        $where['year'] = $post['year'];
        $where['month'] = $post['month'];
        $info = db::name('user_bill')->where($where)->find();
        if (!empty($info)) {
            $this->error('已生成过结算单!');die;
        }
        $w = $post['year'].'-'.$post['month'];
        //取得当前审核通过的订单 usertree = 0 status = 1
        
        $DealList = db::name('deallist');
        $User  = new UserModel();
        $UserData = $User->where([
            'pid_status' => ['EQ',1]
        ])->select();
        $starttime = date('Y-m-d H:i:s',strtotime($w));
        $endtime = date('Y-m-d H:i:s',strtotime("+1 months", strtotime($w)));
        foreach ($UserData as $key => $value) {
            $UserStraightChildID = $User->where([
                'pid_status' => ['EQ',1],
                'pid' => $value['id']
            ])->select();
            $StraightID = array();
            foreach ($UserStraightChildID as $v){
                $StraightID[] =  $v['id'];
            }

            $StraightCount = count($StraightID);
            if($StraightCount < 2){
                continue;//没有收益
            }else{
                foreach ($StraightID as $k=>$v) {
                    $AllLeftMoney = 0;
                    $LeftChildList = getChildrensID($UserData,$v);
                    //实例化订单模型
                    foreach($LeftChildList as $singlelistV){
                        $Leftprice = $DealList->where([
                            'status' => ['EQ',1],
                            'User_id'=> $singlelistV,
                            'tree_status'=> '1',
                        ])->select();
                        foreach($Leftprice as $singleV){
                            $AllLeftMoney += $singleV['deal_price'];
                        }
                    }
                    $money[$k]['money'] = $AllLeftMoney;
                    $money[$k]['id'] = $v;
                }
                $ll[$value['id']] = ($money[0]['money']>$money[1]['money'])?$money[1]['id']:$money[0]['id'];
                foreach ($ll as $k => $v) {
                    // $k自己的ID $v小区的id
                    $LeftChildList = getChildrensID($UserData,$v);
                    foreach($LeftChildList as $singlelistV){
                        $Leftprice = $DealList->where([
                            'status' => ['EQ',1],
                            'User_id'=> $singlelistV,
                            'tree_status'=> '1',
                            'create_time' => array('gt',$starttime),
                            'update_time' => array('lt',$endtime),
                        ])->select();
                        foreach($Leftprice as $singleV){
                            $AllLeftMoney += $singleV['deal_price'];
                        }
                    }
                    $allmoney[$k] = $AllLeftMoney;
                }
            }
        }
        foreach ($allmoney as $key => $value) {
            if (!empty($value)) {
                $bill = array('billno' => $this->createNO('user_bill', 'billno', 'JSD'), 'year' => $year, 'month' => $month, 'money' => $value, 'starttime' => $starttime, 'endtime' => $endtime, 'createtime' => time());
                db::name('user_bill')->data($bill);
                db::name('user_bill')->save();
            }
        }
        $this->success('成功!');
    }
}